package register

import (
	"encoding/json"
	"fmt"
	"log"
	"time"
)

//节点定时上报
type UpdateHandler struct {
	client *Client
}

type NodeUpdate struct {
	ConnNum   int      `json:"conn_num"`  //连接数
	Bandwidth float32  `json:"bandwidth"` //带宽Mbps
	OriginTraffic float64 `json:"origin_traffic"` //回源流量 KB
	CacheTraffic  float64 `json:"cache_traffic"` //缓存命中流量 KB
	Type      int      `json:"type"`      //1:增量上报 2:全量上报
	Files     []string `json:"files"`     //缓存文件url
}

func (s *UpdateHandler) Handle(message []byte) {
	var updateInfo NodeUpdate
	if err := json.Unmarshal(message, &updateInfo); err != nil {
		log.Printf("[UpdateHandler]:get handler json unmarshal err:%s", err.Error())
		return
	}
	log.Printf("[UpdateHandler] updateInfo: %v", updateInfo)
	s.client.NodeStatus.Bandwidth = updateInfo.Bandwidth
	s.client.NodeStatus.ConnNum = updateInfo.ConnNum
	if updateInfo.Type == 2 {
		s.client.NodeStatus.Files = make(map[string]bool)
	}
	if len(updateInfo.Files) > 0 {
		for _, file := range updateInfo.Files {
			s.client.NodeStatus.Files[file] = true
		}
	}
	now := time.Now()
	nowAdd5Min := now.Add(5 * time.Minute)
	day := now.Format("2006_01_02")
	minute := fmt.Sprintf("%s%d", nowAdd5Min.Format("2006_01_02_15_"), (nowAdd5Min.Minute()/5) * 5)
	originTraffic := updateInfo.OriginTraffic / float64(1024)
	cacheTraffic := updateInfo.CacheTraffic / float64(1024)
	log.Printf("[UpdateHandler] day: %v, minute: %v originTraffic:%v, cacheTraffic:%v", day, minute, originTraffic, cacheTraffic)

	err := s.client.server.RDB.ZIncrBy("origin_traffic", originTraffic, day).Err() //MB
	if err != nil {log.Printf("[UpdateHandler] set origin_traffic day err:%s", err.Error())}
	err = s.client.server.RDB.ZIncrBy("origin_traffic", originTraffic, minute).Err() //MB
	if err != nil {log.Printf("[UpdateHandler] set origin_traffic minute err:%s", err.Error())}

	err = s.client.server.RDB.ZIncrBy("cache_traffic", cacheTraffic, day).Err() //MB
	if err != nil {log.Printf("[UpdateHandler] set cache_traffic day err:%s", err.Error())}
	err = s.client.server.RDB.ZIncrBy("cache_traffic", cacheTraffic, minute).Err() //MB
	if err != nil {log.Printf("[UpdateHandler] set cache_traffic minute err:%s", err.Error())}
}
